
#include "UriParser.h"
#include <stdexcept>
#include <stdlib.h>

//-----------------
//--- UriParser ---
//-----------------

UriParser::UriParser(const char *uri)
{
	if (uri == NULL || uri[0] != '/')
		throw std::runtime_error("Bad URI (equal to NULL)");
	//It's first hit.
	if (uri[1] == '\0')
	{
		_type = ShowMuzzle;
	} else
	//It's file request.
	if (uri[1] != '?')
	{
		_type = GetFile;
		_fileName = uri + 1;
	}
	//Parsing arguments.
	else
	{
		_type = UriType::ProcessAction;
		size_t offset = 1;
		std::pair<std::string, std::string> cur;
		do
		{
			//Getting name.
			size_t start = offset + 1;
			offset++;
			while (uri[offset] != '\0' &&
				   uri[offset] != '=' &&
				   uri[offset] != '&')
				offset++;
			if (uri[offset] == '\0')
				throw std::runtime_error("Bad URI (wrong format)");
			cur.first = std::string(uri + start, offset - start);
			//Getting value.
			start = ++offset;
			while (uri[offset] != '\0' &&
				   uri[offset] != '=' &&
				   uri[offset] != '&')
				offset++;
			cur.second = std::string(uri + start, offset - start);
			_args.push_back(cur);
		}
		while (uri[offset] != '\0');
	}
}

bool UriParser::GetIntArgument(const char *name, size_t &value)
{
	const char *res;
	if (GetStringArgument(name, res))
	{
		value = (size_t)atoi(res);
		return true;
	}
	else
	{
		value = 0;
		return false;
	}
}

bool UriParser::GetStringArgument(const char *name, const char *&value)
{
	for (size_t i = 0; i < _args.size(); i++)
		if (_args[i].first == name)
		{
			value = _args[i].second.c_str();
			return true;
		}
	value = NULL;
	return false;
}
